package hos.bus;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;

import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>Title: LiveBus </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @version : 1.0
 * @date : 2022/3/31 20:43
 */
public class LiveBus {
    static final ConcurrentHashMap<String, LiveData<?>> eventMap = new ConcurrentHashMap<>();
    static final ConcurrentHashMap<String, LiveData<?>> onceEventMap = new ConcurrentHashMap<>();

    @NonNull
    @SuppressWarnings("unchecked")
    public static <T> StickyLiveData<T> with(@NonNull String eventName) {
        //基于事件名称 订阅 分发消息
        // 由于一个livedata 只能发送一种数据类型，所以 不同的event 事件，需要使用不同的livedata实例 分发
        LiveData<?> liveData = eventMap.get(eventName);
        if (liveData == null) {
            liveData = new StickyLiveData<T>(eventName);
            eventMap.put(eventName, liveData);
        }
        if (liveData instanceof StickyLiveData) {
            return (StickyLiveData<T>) liveData;
        }
        throw new RuntimeException(eventName + " is not StickyLiveData ");
    }

    @NonNull
    @SuppressWarnings("unchecked")
    public static <T> OnceLiveData<T> once(@NonNull String eventName) {
        //基于事件名称 订阅 分发消息
        // 由于一个livedata 只能发送一种数据类型，所以 不同的event 事件，需要使用不同的livedata实例 分发
        LiveData<?> liveData = onceEventMap.get(eventName);
        if (liveData == null) {
            liveData = new OnceLiveData<T>(eventName);
            onceEventMap.put(eventName, liveData);
        }
        if (liveData instanceof OnceLiveData) {
            return (OnceLiveData<T>) liveData;
        }
        throw new RuntimeException(eventName + " is not OnceLiveData ");
    }

    protected static void remove(@NonNull String eventName) {
        eventMap.remove(eventName);
        onceEventMap.remove(eventName);
    }

    @NonNull
    public static LifecycleHandler on(@NonNull LifecycleOwner lifecycleOwner) {
        return new LifecycleHandler(lifecycleOwner);
    }

}
